//
//  ST_PrivateChatViewController+sendMessage.swift
//  BTVideo
//
//  Created by DouLei on 2019/7/22.
//  Copyright © 2019 DouLei. All rights reserved.
//

import Foundation
import UIKit
import SwifterSwift
import MJRefresh
import NIMSDK




extension ST_PrivateChatViewController{
    
    
    func modify_upload_image_u_uid(_ id:String,rcID:String){
        
        /*
        let q = dispatch_queue_global_t(label: "createBrowerQueue")
        
        q.sync() {
            
            //            print("modify_upload_image_u_uid之前",self.originalImageUUIDArray)
            
            var idx:Int?
            for (i,item) in self.originalImageUUIDArray.enumerated(){
                
                if item == id{
                    idx = i
                    break
                }
            }
            
            if let d = idx{
                self.originalImageUUIDArray[d] = rcID
            }
            
            //            print("modify_upload_image_u_uid之后",self.originalImageUUIDArray)
        }
        */
        
    }
    
    
    func send_emoji_message(emoji:BTEmojiItemModel) {
        

        let model = ST_DTChatMessage()
        
        model.chatID = sessionID
        
        model.messageTime = Int64(Date().timeIntervalSince1970)
        
        model.cellStyle = .CustomNewEmoji
        
        model.direction = .send
        
        guard let account = ST_BTUserInfoManager.shared.current_account_info,let userInfo = account.userinfo else { return }
        
        model.portraitUri = userInfo.avatar
        
        model.userName = userInfo.nickname
        
        let emojiModel = ST_BTIMEmojiMessageModel()
        
        emojiModel.imageUrl = emoji.image
        
        emojiModel.name = emoji.name
        
        model.emoji = emojiModel
        
//        model.uploadStatus = .success
        
        model.figureFrame()
        
        self.sendInstantMsg(message: model)
        
    }
    
    func send_goods_message(goods:ST_BTIMGiftMessageModel,type:ST_DTChatCellStyle = .goodsType) {
        

        let model = ST_DTChatMessage()
        
        model.chatID = sessionID
        
        model.messageTime = Int64(Date().timeIntervalSince1970)
        
        model.cellStyle = type
        
        model.direction = .send
        
        guard let account = ST_BTUserInfoManager.shared.current_account_info,let userInfo = account.userinfo else { return }
        
        model.portraitUri = userInfo.avatar
        
        model.userName = userInfo.nickname
        
        model.goods = goods
        
//        model.uploadStatus = .success
        
        model.figureFrame()
        
        self.sendInstantMsg(message: model)
        
    }
    
    func sendRedPacketMessage(attach:ST_Custom255AttachmentModel) {
        
        let model = ST_DTChatMessage()
        
        model.chatID = sessionID
        
        model.messageTime = Int64(Date().timeIntervalSince1970)
        
        model.cellStyle = .redPacket
        
        model.direction = .send
        
        guard let account = ST_BTUserInfoManager.shared.current_account_info,let userInfo = account.userinfo else { return }
        
        model.portraitUri = userInfo.avatar
        
        model.userName = userInfo.nickname
        
        model.customAttachment255 = attach
        
//        model.uploadStatus = .success
        
        model.figureFrame()
        
        self.sendInstantMsg(message: model)
        
    }
    
    
    func sendRedPacketOfReceivedMessage(attach:ST_Custom255AttachmentModel) {
        
        let model = ST_DTChatMessage()
        
        model.chatID = sessionID
        
        model.messageTime = Int64(Date().timeIntervalSince1970)
        
        model.cellStyle = .redPacketReceived
        
        model.direction = .send
        
        guard let account = ST_BTUserInfoManager.shared.current_account_info,let userInfo = account.userinfo else { return }
        
        model.portraitUri = userInfo.avatar
        
        model.userName = userInfo.nickname
        
        model.customAttachment255 = attach
        
//        model.uploadStatus = .success
        
        model.figureFrame()
        
        self.sendInstantMsg(message: model)
        
        ST_BTUserInfoManager.shared.increase_income(value: attach.redPacketIncome.double, msgSendDate: Date())
        
    }
    
    
    func send_text_message(text:String) {
        
        if text.count < 1{
           return
       }

        let model = ST_DTChatMessage()
        
        model.chatID = sessionID
        
        model.messageTime = Int64(Date().timeIntervalSince1970)
        
        model.cellStyle = .Text
        
        model.direction = .send
        
        guard let account = ST_BTUserInfoManager.shared.current_account_info,let userInfo = account.userinfo else { return }
        
        model.portraitUri = userInfo.avatar
        
        model.userName = userInfo.nickname
        
        model.chatText = text
        
//        model.uploadStatus = .success
        
        model.figureFrame()
        
        self.sendInstantMsg(message: model)
        
    }
    
    func send_image_message(thumbnailPath:String,imagePath:String,size:CGSize,isSnapChat:Bool = false) {
        
        if self.judgementSendMsgOperation() == false{
            return
        }
        
        let model = ST_DTChatMessage()
        
        model.chatID = sessionID
        
        guard let account = ST_BTUserInfoManager.shared.current_account_info,let userInfo = account.userinfo else { return }
        
        model.portraitUri = userInfo.avatar
        
        model.userName = userInfo.nickname
        
        
        model.messageTime = Int64(Date().timeIntervalSince1970)
        
        if isSnapChat{
            model.cellStyle = .snapChat
//            model.chatImageSize = CGSize.init(width: ScreenWidth, height: 140+15)
        }else{
            model.cellStyle = .Image
        }
        
        model.chatImageSize = size
        
        model.direction = .send
        
        model.thumbnailImageLocalPath = thumbnailPath
        
        model.imageLocalURL = imagePath
        
//        model.uploadStatus = .success
        
        model.figureFrame()
        
        self.sendInstantMsg(message: model)
        
    }
    
    
    func send_video_message(thumbnailPath:String,size:CGSize,videoPath:String) {
  
        if self.judgementSendMsgOperation() == false{
            return
        }
        
        let model = ST_DTChatMessage()
        
        model.chatID = sessionID
        
        guard let account = ST_BTUserInfoManager.shared.current_account_info,let userInfo = account.userinfo else { return }
        
        model.portraitUri = userInfo.avatar
        
        model.userName = userInfo.nickname
        
        model.messageTime = Int64(Date().timeIntervalSince1970)
        
        model.cellStyle = .Video
        
        model.direction = .send
        
        model.videoWidth = size.width
        
        model.videoHeight = size.height
        
//        视频本身内容
        model.videoLocalPath = videoPath
        
        model.videoThumbnailPath = thumbnailPath
        
//        model.uploadStatus = .success
        
        model.figureFrame()
        
        self.sendInstantMsg(message: model)
        
    }
    
    
    func send_voice_message(path:String,duration:Int) {
        
        if self.judgementSendMsgOperation() == false{
            return
        }
        let model = ST_DTChatMessage()
        
        model.chatID = sessionID
        
        guard let account = ST_BTUserInfoManager.shared.current_account_info,let userInfo = account.userinfo else { return }
        
        model.portraitUri = userInfo.avatar
        
        model.userName = userInfo.nickname
        
        model.messageTime = Int64(Date().timeIntervalSince1970)
        
        model.cellStyle = .voice
        
        model.direction = .send
        
//                语音本身内容
        model.voiceLocalPath = path
        
        model.voiceDuration = duration
        
        
        
//        model.uploadStatus = .success
        
        model.figureFrame()
        
        self.sendInstantMsg(message: model)
        
    }
    
    /// 女性只能邀约语音、视频通话
    func sendFemaleInviteMessage(type:Int){
        
        let model = ST_DTChatMessage()
        model.chatID = self.sessionID
        model.messageTime = Int64(Date().timeIntervalSince1970)
        model.cellStyle = .femaleInviteChat
        model.femaleInviteChatType = type
        model.direction = .send
        
        guard let account = ST_BTUserInfoManager.shared.current_account_info,let userInfo = account.userinfo else { return }
        
        model.portraitUri = userInfo.avatar
        
        model.userName = userInfo.nickname
        
        model.figureFrame()
        
        sendInstantMsg(message: model)
        
    }
    
    func sendInstantMsg(message:ST_DTChatMessage){
        
        if ST_BTUserInfoManager.shared.confined_to_ticket(){
            
            let vc = ST_TicketViewController()
            
            vc.from = .mainIndexConfined
            
            GlobalPresent(toController: vc)
            
            return
        }
        
        
        
        //        禁言
        if ST_BTUserInfoManager.shared.additional_attributes?.mute == 3{
            
            self.toast(text: "您已被禁言了")
            
            return
        }
        
        if self.sessionID != DIALOGUE_ASSISTANT_SESSION_ID {
            if restrictFemaleFace(){
                return
            }
        }
        
        
        if let check = ST_BTUserInfoManager.shared.additional_attributes?.phoneBound{
            
            let limitSet:[ST_DTChatCellStyle] = [.Text,.Image,.snapChat,.CustomNewEmoji,.voice,.Video]
            
            if !check && limitSet.contains(message.cellStyle)  {
             
                _ = BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self)
                
                return
            }
            
        }else{
            
            self.toast(text: "当前网络环境不太稳定，请稍等片刻~")
            
            return
        }
        
        
        
        
        
        
        let coin = ST_DTChatMessageSendHander.shared.sendRequreCoinMap[message.chatID] ?? 0
        
//        需要扣费的 消息类型
        if  message.check_send_with_create_remote_ext(send_requre_coin: coin, source: self.source) == false{
            
            let rechargeMsg = ST_DTChatMessage()
            rechargeMsg.cellStyle = .recharge
            rechargeMsg.cellHeight = 140
            self.append_model(rechargeMsg)
            
            ST_RechargeViewController.toast()
            
            
            return
        }
        
        
        
        ST_DTChatMessageSendHander.shared.sendMessage(message: message)
        
    }
    
    
    /**
     能否发送消息
     */
    func judgementSendMsgOperation() -> Bool {
        
        switch self.prevent_chat {
        case .verifyFace:
            self.toast(text: "真人认证了才能继续对话")
            return false
        default:
            return true
        }
    }
    
    
}

//MARK: - record audio
extension ST_PrivateChatViewController:DPChatToolBarAudioDelegate{
    
    
    func dpAudioRecordingFinish(with audioData: Data!, withBodyString body: String!) {
        
        print("录制完成✅body:",body ?? "ERROR")
        
        guard let duration = body.int,let url = saveAudioToDocument(audioData: audioData) else { return  }
        
        self.send_voice_message(path: url.path, duration: duration)
        
        record_audio_sign_view.isHidden = true
    }
    
    func dpAudioRecording(){
        recordingSign()
    }
    
    func dpAudioStartRecording(_ isRecording: Bool) {
        
        recordingSign()
    }
    
    func recordingSign(){
        record_audio_sign_view.isHidden = false
        record_audio_sign_view.image = ST_ImageUtils.imageName("n_私信_bj_发送语音")
        speak_power_view.isHidden = false
        
        self.last_play_audio_cell?.stop_play_audio()
    }
    
    func dpAudioSpeakPower(_ power: Float) {
        
        record_audio_sign_view.isHidden = false
        var p = Int(power*10/2)
        if p == 0{
            p = 1
        }
        let str = "n_私信_icon_发送语音0\(p)"
        let image = UIImage.init(named: str)
        speak_power_view.image = image
//        print("私信音响大小----",image,"----是否隐藏:",speak_power_view.isHidden)
        
    }
    
    
    
    func dpCanCancelAudioRecording() {
        
        record_audio_sign_view.isHidden = false
        record_audio_sign_view.image = ST_ImageUtils.imageName("n_私信_icon_发送语音取消")
        speak_power_view.isHidden = true
    }
    
    func dpAudioRecordingFail(_ reason: String!) {
        
        if reason == "说话时间太短"{
            record_audio_sign_view.isHidden = false
            record_audio_sign_view.image = ST_ImageUtils.imageName("n_私信_icon_录制时间太短")
            speak_power_view.isHidden = true
            
            main_thread_execute(afterDelay: 1) {
                self.record_audio_sign_view.isHidden = true
            }
        }else{
            record_audio_sign_view.isHidden = true
//            print("录制失败",reason)
        }
    }
    
//    MARK: - Tools
    private func saveAudioToDocument(audioData:Data)->URL?{
        // get the documents directory url
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        // choose a name for your image
        let fileName = UUID().uuidString
        // create the destination file url to save your image
        let fileURL = documentsDirectory.appendingPathComponent(fileName)
        // get your UIImage jpeg data representation and check if the destination file url already exists
        do {
            // writes the image data to disk
            try audioData.write(to: fileURL)
            //                print("FILE--URL-2:",fileURL)
            return fileURL
            
        } catch {
            
            print("saveAudioToDocument -- error saving file: \(error)")
            
            return nil
        }
    }
    
}



//MARK: - Play Audio
extension ST_PrivateChatViewController:ST_d_t_voice_play_protocol{
    
    func playAudio(message:ST_DTChatMessage,currentCell:ST_DTVoiceChatCell)  {
        
        last_play_audio_message = message
        if let lastCell = self.last_play_audio_cell,lastCell != currentCell{
            
            if self.tableView.visibleCells.contains(lastCell){
                
                lastCell.stop_play_animation()
                self.audioPlayer.stop_playing()
            }
        }
        
        self.last_play_audio_cell = currentCell
        
        if let localPath = message.voiceLocalPath,FileManager.default.fileExists(atPath: localPath),let localData = localPath.load_data_from_disk(){
            
            self.audioPlayer.startPlay(with: localData)
            
            print("播放本地Audio文件:\(localPath)")
            
        }else if let remoteUrl = message.voiceRemoteUrl{
            
            print("播放远程Audio文件:\(remoteUrl)")
            
            self.audioPlayer.startPlay(withURL: remoteUrl)
        }
        
        
        
    }
    
    func stop_play_audio(message:ST_DTChatMessage)  {
        self.audioPlayer.stop_playing()
    }
}



extension ST_PrivateChatViewController:ST_TianSendMessageStatusProtocol{
    
    func sendMessageCheckReceiveFirst() -> Bool {
//        数据大于0  并且没有我收到的
        if  self.data.count > 0 && self.data.contains(where: {$0.direction == .receive}) == false{
            
            return false
        }
        return true
    }
    
    
    func sendMessagePreview(message: ST_DTChatMessage) {
        self.append_model(message)
        
        if message.cellStyle == .femaleInviteChat,let t = message.femaleInviteChatType{
            
            ST_PrivateInviteChatTimesLog.insert(type: t, targetId: message.chatID)
            
        }
        
    }
    
    
    
    func sendMessageProgress(id: String, progress: Int32) {
     
        
        self.data.first(where: ({$0.uuid == id}))?.uploadStatus = .uploading
        self.data.first(where: ({$0.uuid == id}))?.uploadImageProgress = progress
        
        self.updateCellIndicator(msgID: id)
        
    }
    
    func sendMessageFinish(id: String, error: Error?) {
        
        var status = ST_DTChatUploadStatus.success
        
        if let err = error as NSError?{
            status = .failure
            print("发送云信消息失败：",err)
            
//            文本违规
            if err.code == SENSITIVE_CODE{
                
                let model = ST_DTChatMessage()
                
                let m = ST_Custom264AttachmentModel()
                
                model.customTips = m
                
                model.chatID = sessionID
                
                guard let account = ST_BTUserInfoManager.shared.current_account_info,let userInfo = account.userinfo else { return }
                
                model.portraitUri = userInfo.avatar
                
                model.userName = userInfo.nickname
                
                model.messageTime = Int64(Date().timeIntervalSince1970)
                
                model.cellStyle = .tips
                
                model.direction = .send
                
                model.chatText = "你发送的消息存在违规信息，请文明聊天，共同构建和谐氛围"
                
                model.figureFrame()
                
                self.sendInstantMsg(message: model)
            }
            
        }
        
        self.data.first(where: ({$0.uuid == id}))?.uploadStatus = status
        
        self.updateCellIndicator(msgID: id)
    }
    
    
    fileprivate func updateCellIndicator(msgID:String){
        
        main_thread_execute {
            
            for cell in self.tableView.visibleCells{
                
                if let iCell = cell as? ST_DTChatCell,iCell.message.uuid == msgID{
                    
                    iCell.setting_uplaod_status()
                    
                }
            }
        }
    }
    
}
